<template>
  <!-- 扣款设置表单 -->
  <div>
    <el-form ref="deductionFormRef" :model="deductionForm" :rules="deductionRules" label-width="120px">
      <!-- 选择部门 -->
      <el-form-item label="请选择部门：" prop="departmentId">
        <el-cascader
          v-model="deductionForm.departmentId"
          :options="departmentList"
          :props="{ expandTrigger: 'hover', label: 'name', value: 'id', emitPath: false }"
          separator="-"
          @change="onChangeDepartment"
          @blur.native.capture="$refs.deductionFormRef.validateField('departmentId')"
        />
      </el-form-item>
    </el-form>
    <!-- 扣款设置列表 -->
    <ul v-if="deductionForm.deductionList.length !== 0" class="deduction-list">
      <!-- 扣款设置列表项 -->
      <li v-for="item in deductionForm.deductionList" :key="item.id" class="deduction-item">
        <!-- 扣款设置标题 -->
        <div class="deduction-title">
          {{ deductionName[item.dedTypeCode] }}&nbsp;
          <el-switch
            v-model="item.isEnable"
          />
        </div>
        <!-- 扣款设置内容，不是旷工设置时显示 -->
        <div v-if="!parseInt(item.isAbsenteeism)" class="deduction-content">
          <!-- 时间段限制 -->
          <div class="period-limit">
            <!-- 时间段下限 -->
            <div class="period-lower-limit indentation">
              {{ deductionName[item.dedTypeCode].slice(0, 2) }}≤
              <span class="input-span">
                <el-input v-model="item.periodLowerLimit" :class="{ 'input': true, 'is-invalid': item.periodLowerLimit === '' }" size="medium" />
                <span v-if="item.periodLowerLimit === ''" class="error-message">不能为空</span>
              </span>
              分钟
            </div>
            <!-- 次数限制 -->
            <div class="times-limit">
              <!-- 次数下限 -->
              <div class="times-lower-limit double-indentation">
                {{ deductionName[item.dedTypeCode].slice(0, 2) }}≤
                <span class="input-span">
                  <el-input v-model="item.timesLowerLimit" :class="{ 'input': true, 'is-invalid': item.timesLowerLimit === '' }" size="medium" />
                  <span v-if="item.timesLowerLimit === ''" class="error-message">不能为空</span>
                </span>
                次，每次扣款
                <span class="input-span">
                  <el-input v-model="item.dedAmonutLowerLimit" :class="{ 'input': true, 'is-invalid': item.dedAmonutLowerLimit === '' }" size="medium" />
                  <span v-if="item.dedAmonutLowerLimit === ''" class="error-message">不能为空</span>
                </span>
                元
              </div>
              <!-- 次数上限 -->
              <div class="times-upper-limit double-indentation">
                {{ deductionName[item.dedTypeCode].slice(0, 2) }}>
                <el-input v-model="item.timesUpperLimit" class="input" size="medium" disabled />
                次，每次扣款
                <span class="input-span">
                  <el-input v-model="item.dedAmonutUpperLimit" :class="{ 'input': true, 'is-invalid': item.dedAmonutUpperLimit === '' }" size="medium" />
                  <span v-if="item.dedAmonutUpperLimit === ''" class="error-message">不能为空</span>
                </span>
                元
              </div>
            </div>
          </div>
          <!-- 旷工限制 -->
          <div class="absence-limt">
            <!-- 时间段上限 -->
            <div class="period-upper-limit indentation">
              {{ deductionName[item.dedTypeCode].slice(0, 2) }}>
              <el-input v-model="item.periodUpperLimit" class="input" size="medium" disabled />
              分钟
            </div>
            <!-- 旷工次数限制 -->
            <div class="absence-times-limt">
              <div class="absence-times-upper-limt double-indentation">
                {{ deductionName[item.dedTypeCode].slice(0, 2) }}>
                <el-input v-model="item.absenceTimesUpperLimt" class="input" size="medium" disabled />
                次，每次旷工
                <span class="input-span">
                  <el-input v-model="item.absenceDays" :class="{ 'input': true, 'is-invalid': item.absenceDays === '' }" size="medium" />
                  <span v-if="item.absenceDays === ''" class="error-message">不能为空</span>
                </span>
                天
              </div>
            </div>
          </div>
        </div>
        <!-- 扣款设置内容，是旷工设置时显示 -->
        <div v-else class="deduction-content">
          <!-- 旷工设置 -->
          <div class="absence-deduction indentation">
            旷工按
            <span class="input-span">
              <el-input v-model="item.fineSalaryMultiples" :class="{ 'input': true, 'is-invalid': item.fineSalaryMultiples === '' }" size="medium" />
              <span v-if="item.fineSalaryMultiples === ''" class="error-message">不能为空</span>
            </span>
            倍工资处罚
          </div>
        </div>
      </li>
    </ul>
  </div>
</template>

<script>
import { getDepartmentListAPI } from '@/api/department'
import { transListToTreeData } from '@/utils'
import { getDeductionSettingAPI, updateDeductionSettingAPI } from '@/api/attendance'

const defaultFormData = {
  departmentId: 2, // 部门id
  deductionList: [] // 扣款设置列表
}

export default {
  name: 'DeductionConfig',
  data() {
    return {
      departmentList: [], // 部门列表
      //  扣款设置表单数据
      deductionForm: { ...defaultFormData },
      // 扣款设置表单校验规则
      deductionRules: {
        departmentId: [
          { required: true, message: '请选择部门', trigger: ['blur', 'change'] }
        ]
      },
      // 扣款设置名称
      deductionName: {
        '51000': '迟到扣款',
        '52000': '早退扣款',
        '53000': '旷工扣款'
      }
    }
  },
  async created() {
    // 获取部门列表
    await this.getDepartmentList()
    await this.onChangeDepartment()
  },
  methods: {
    // 获取部门列表
    async getDepartmentList() {
      const list = await getDepartmentListAPI()
      this.departmentList = transListToTreeData(list, 0)
    },
    // 修改了选中的部门
    async onChangeDepartment() {
      this.deductionForm.deductionList = await getDeductionSettingAPI(this.deductionForm.departmentId)
    },
    // 保存考勤扣款规则
    async saveDeductionSetting() {
      // 校验表单数据是否通过校验
      let isValid = true
      //  判断扣款设置列表是否有数据
      if (this.deductionForm.deductionList.length !== 0) {
        // 校验表单设置列表中是否有必要数据为空
        this.deductionForm.deductionList.forEach(item => {
          if (item.dedTypeCode === '51000' || item.dedTypeCode === '52000') {
            if (item.periodLowerLimit === '' || item.timesLowerLimit === '' || item.dedAmonutLowerLimit === '' || item.dedAmonutUpperLimit === '' || item.absenceDays === '') {
              isValid = false
            }
          } else {
            if (item.fineSalaryMultiples === '') {
              isValid = false
            }
          }
        })
      } else {
        isValid = false
      }
      // 校验部门表单
      this.$refs.deductionFormRef.validate(async valid => {
        // 通过校验
        if (valid && isValid) {
          await updateDeductionSettingAPI(this.deductionForm.deductionList)
          // 提示保存成功
          this.$message.success('扣款设置保存成功')
          // 关闭弹窗
          this.$emit('close')
        } else {
          // 未通过校验
          this.$message.error('请填写完整数据')
          return
        }
      })
    },
    // 重置表单数据
    resetFormData() {
      this.deductionForm = { ...defaultFormData }
    }
  }
}
</script>

<style lang="scss" scoped>
ul {
  list-style: none;
  margin-block-start: 0;
  margin-block-end: 0;
  padding-inline-start: 0;
}
.deduction-list {
  margin-bottom: 20px;
  border-top: 1px solid #eee;
  :hover {
    background-color: #f7f8f9;
  }
  .deduction-item {
    padding: 20px 10px;
    border-bottom: 1px solid #eee;
    line-height: 60px;
    .deduction-title {
      display: flex;
      align-items: center;
    }
    .deduction-content {
      // 缩进
      .indentation {
        padding-left: 80px;
      }
      // 双倍缩进
      .double-indentation {
        padding-left: 160px;
      }
      // 输入框样式
      .input {
        display: inline-block;
        width: 60px;
      }
    }
  }
}
.input-span {
  position: relative;
  .error-message {
    display: block;
    position: absolute;
    top: 30px;
    left: 5px;
    font-size: 12px;
    color: red;
    line-height: 12px;
  }
  ::v-deep .is-invalid {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}
</style>
